package com.oss.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.oss.model.Link;
import com.oss.validation.LinkValidator;

/**
 * @author xueqiang.mi
 * @date 2010-2-8
 */
@Controller
public class LinkController extends BaseController {

	@RequestMapping(value = "/shareLink.do", method = RequestMethod.POST)
	public String addHandler(Link link, BindingResult result,
			SessionStatus status) {
		new LinkValidator().validate(link, result);
		if (result.hasErrors()) {
			return "linkForm";
		} else {
			// set created author for link
			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			if (user != null) {
				link.setCreatedAuthor(user);
				// enables the projects added by google user
				link.setEnabled(true);
			} else {
				// disables the projects added by anonymous
				link.setEnabled(false);
			}
			lnkService.add(link);

			status.setComplete();
			return "redirect:/project.do?id=" + link.getPrj();
		}
	}

	@RequestMapping(value = "/shareLink.do", method = RequestMethod.GET)
	public String addLink(Model model,
			@RequestParam(value = "pid", required = false) String pid) {
		Link link = new Link();
		link.setPrj(pid);
		model.addAttribute(link);

		return "linkForm";
	}

	@RequestMapping("/links.do")
	public String links(
			Model model,
			@RequestParam(value = "pageIndex", required = false) Long pageIndex,
			@RequestParam(value = "pageSize", required = false) Long pageSize) {
		if (pageIndex == null || pageSize == null) {
			return "redirect:/links.do?pageIndex=1&pageSize="
 + PRJ_MEDIUM_SIZE;
		}
		pageIndex = pageIndex > 0 ? pageIndex : 1;
		pageSize = pageSize > 50 ? 50 : (pageSize > 0 ? pageSize : 10);
		model.addAttribute("links", lnkService.getLatestLnks(pageIndex,
				pageSize));
		return "links";
	}
}
